package com.imist.demo;

import com.imist.jdbcutil.JDBCUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCDemo4 {

    /**
     * 测试SQL注入漏洞的方法;
     * 原因：参数包含了SQL关键字导致的错误或者异常
     */
    @Test
    public void testLogin() {
        //boolean isLoginSuccess = login("222 ' or '1=1 ", "bbb");
        //boolean isLoginSuccess = login("222 ' --  ", "bbb");
        boolean isLoginSuccess = login2("222", "bbb");
        if (isLoginSuccess) {
            System.out.println("登陆成功");
        } else {
            System.out.println("登陆失败");
        }
    }

    public boolean login(String username, String password) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        boolean flag = false;
        try {
            connection = JDBCUtil.getConnection();
            statement = connection.createStatement();
            //注意字符串连接
            String sql = "SELECT * FROM user WHERE username = '" + username + "' AND password = '" + password + "' ";
            resultSet = statement.executeQuery(sql);
            if (resultSet.next()) {
                flag = true;
            } else {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection, statement, resultSet);
        }
        return flag;
    }

    /**
     * 预处理语句编写SQL用占位符来表示变量，防止SQL注入，提高了编译效率，简化SQL语句编写
     * @param username
     * @param password
     * @return
     */
    public boolean login2(String username, String password) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        boolean flag = false;
        try {
            connection = JDBCUtil.getConnection();
            //注意字符串连接
            String sql = "SELECT * FROM user WHERE username = ? AND password = ? ";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                flag = true;
            } else {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection, preparedStatement, resultSet);
        }
        return flag;
    }

}
